import time
import uuid
from nicegui import ui
from nicegui import events, ui
import json
import pprint

from pkg_resources import require


class StreetView:
    def __init__(self, tabs: ui.tabs, value: str) -> None:
        self.rec_layer = None
        with ui.row().classes("w-full"):
            with ui.card().style("width:70%;height:450px"):
                ui.label("选择下载区域(左侧矩形按钮)").tailwind("text-lg")
                m = ui.leaflet(
                    center=(25.088403165474332, 121.56754482561634),
                    zoom=12,
                    draw_control={
                        "draw": {
                            "polygon": False,
                            "marker": False,
                            "circle": False,
                            "rectangle": True,
                            "polyline": False,
                            "circlemarker": False,
                        },
                        "edit": False,
                    },
                ).style("height: 100%")
                self.m = m
                m.on("draw:created", self.handle_draw)
            with ui.card().style("height:450px;width:20%"):
                ui.label("下载区域").tailwind("text-lg")
                self.json_editor = ui.log().style("height:400px;width:100%")
                # 重置按钮
                with ui.row().style("justify-content: center").style(
                    "margin-top: 10px"
                ):
                    ui.button("重置").on("click", self.reset)
                    ui.button("添加到下载任务").on("click", self.download)
                    # console.log(self.json_editor)
                    ui.checkbox("添加到任务后自动开始下载")

        with ui.card().style("width:91.2%"):
            ui.label("任务列表").tailwind("text-lg")
            # hr
            ui.add_body_html("<hr>")

            # 任务列表
            self.columns = [
                # 任务ID
                {
                    "name": "id",
                    "label": "任务id",
                    "field": "id",
                    "required": True,
                    "align": "left",
                    },
                {
                    "name": "任务名称",
                    "label": "任务名称",
                    "field": "name",
                    "required": True,
                    "align": "left",
                },
                {
                    "name": "任务状态",
                    "label": "任务状态",
                    "field": "status",
                    "required": True,
                    "align": "left",
                },
                {
                    "name": "progress",
                    "label": "progress",
                    "field": "progress",
                    "required": True,
                    "align": "left",
                },
                {
                    "name": "action",
                    "field": "action",
                    "action": "操作",
                    "label": "操作",
                    "align": "center",
                    "required": False,
                },
            ]

            self.rows = [
                {
                    "name": "任务1",
                    "status": "未开始",
                    "progress": "0%",
                    "id": uuid.uuid1(),
                },
                {
                    "name": "任务2",
                    "status": "未开始",
                    "progress": "0%",
                    "id": uuid.uuid1(),
                },
                {
                    "name": "任务2",
                    "status": "未开始",
                    "progress": "0%",
                    "id": uuid.uuid1(),
                },
                {
                    "name": "任务2",
                    "status": "未开始",
                    "progress": "0%",
                    "id": uuid.uuid1(),
                },
                {
                    "name": "任务2",
                    "status": "未开始",
                    "progress": "0%",
                    "id": uuid.uuid1(),
                },
                {
                    "name": "任务2",
                    "status": "未开始",
                    "progress": "0%",
                    "id": uuid.uuid1(),
                },
                {
                    "name": "任务2",
                    "status": "未开始",
                    "progress": "0%",
                    "id": uuid.uuid1(),
                },
                {
                    "name": "任务2",
                    "status": "未开始",
                    "progress": "0%",
                    "id": uuid.uuid1(),
                },
            ]

            self.table = ui.table(columns=self.columns, rows=self.rows,pagination=4).style(
                "width:100%"
            )
            # self.table.add_slot()
            # use add slot to add a button on last column
            self.table.add_slot(
                "body-cell-action",
                r"""                                
                    <q-td key="action" :props="props">
                        <q-btn color="primary" label="开始下载" size="sm" class="q-mr-sm"/> 
                        <q-btn color="warning" label="暂停下载" size="sm" class="q-mr-sm"/> 
                        <q-btn color="negative" label="删除任务" size="sm" class="q-mr-sm"/> 
                        <q-btn color="info" label="可视化" size="sm" /> 
                    </q-td>
                """,
            )

            self.table.add_slot(
                "body-cell-progress",
                r"""            
                 <q-td key="progress" :props="props">
                    <q-linear-progress
                        :value="parseFloat(props.row.progress)"
                        color="primary"
                        track-color="blue-2"
                        size="15px"
                    />
                </q-td>                
                """,
            )

    def download(self, e: events.GenericEventArguments):
        ui.notify("开始下载", type="info")

    def reset(self, e: events.GenericEventArguments):
        # self.m.clear()
        # 确保图层对象存在
        if hasattr(self, "rec_layer") and self.rec_layer in self.m.layers:
            self.m.remove_layer(self.rec_layer)
        self.m.layers.clear()
        self.m.update()
        # 删除创建的图层
        self.json_editor.clear()
        self.json_editor.update()

    def handle_draw(self, e: events.GenericEventArguments):
        if e.args["layerType"] == "marker":
            self.m.marker(
                latlng=(
                    e.args["layer"]["_latlng"]["lat"],
                    e.args["layer"]["_latlng"]["lng"],
                )
            )
            self.lon_lat_json = {
                "lonlat": [
                    e.args["layer"]["_latlng"]["lat"],
                    e.args["layer"]["_latlng"]["lng"],
                ]
            }
        if e.args["layerType"] == "polygon":
            self.m.generic_layer(name="polygon", args=[e.args["layer"]["_latlngs"]])
        if e.args["layerType"] == "rectangle":
            self.rec_layer = self.m.generic_layer(
                name="rectangle", args=[e.args["layer"]["_latlngs"]]
            )
            # console.log(e.args['layer']['_latlngs'])
            print(e.args["layer"]["_latlngs"])
            # update self.json_editor to show the lonlat
            value = str({"lonlat": e.args["layer"]["_latlngs"]}).replace("'", '"')
            # format value to pretty json

            value = json.loads(value)
            value = pprint.pformat(value)
            value = value.replace("{'lonlat':", "").replace("]]}", "]]")
            # 去除前后空格
            value = value.strip()
            # 第一个[[换行
            value = value.replace("[", "[\n")
            # 第一个]]换行
            value = value.replace("]", "\n]")

            # split by \n, each line strip then concat by \n
            value = "\n".join([i.strip() for i in value.split("\n")])

            self.json_editor.push(value)
            self.json_editor.update()
